<?php
namespace app\manage\controller;
use think\Controller;
use think\Db;
class Affairengineering extends Controller {
	function __construct() {
		session('user.id', 20);
	}
	
	private $id; //流水号
	static $type = 3; //事务类型id
	public function apply($input){
		return $this->affairApply($input);
		//生成事务
	}
	
	//事务初始化
	private function affairApply($input){
		$id = Db::table('affair_table')->insertGetId([
					'type' => self::$type,
					'content' => '',
					'opinions' => '',
					'create_by' => $input['uid'],
					'charge' => $input['charge'],
					'create_t' => $input['time'],
					'contract_amount' => $input['contract_amount'],
					'amount' => $input['amount'],
					'cur_step' => 0,
					'cur_person' => '',
					'order_no' => $input['order_no'],
					'order_name' => $input['order_name'],
					'accessory' => isset($input['accessory']) ? $input['accessory'] : '', 
			]);
		if(!$id) return ['status' => 0, 'msg' => '操作失败,请重试!'];
        $this->nextStep($id, true);

		return ['status' => 1, 'msg' => '操作成功'];
	}
	
	//初始化下一步
	private function nextStep($id, $result){
		$row = Db::table('affair_table')->field('id,cur_step,create_by,final_opinion,cur_person,charge,order_name')->find($id);
		$res = Db::table('affair_default_process')->field('content,promoter')->where(['type' => self::$type])->find();
		$content = json_decode($res['content'], true);
		
		//如果为第0步,判断下一步直接到哪里，
		$userModel = new \app\manage\controller\User();
		if($row['cur_step'] == 0){
			$promoter = json_decode($res['promoter'], true);
			
			//发起人直达某个步骤
			if(isset($promoter['persons'][$row['charge']])){
				//persons
				$row['cur_step'] = $promoter['persons'][$row['charge']]-1;
			}else{
				//duty
				$temp = $userModel->profile($row['charge']);
				$duty = [];
				$max = 0;
				foreach ($temp['role'] as $v) {
					if(isset($promoter['duty'][$v])){
						if($promoter['duty'][$v] > $max) $max = $promoter['duty'][$v]; 
					}
				}
				if($max > 0) $row['cur_step'] = $max-1;
			}
		}
		
		//将当前处理人意见加入到历史意见中
		$cur_person = json_decode($row['cur_person'], true) ? json_decode($row['cur_person'], true) : [];
		$final_opinion = json_decode($row['final_opinion'], true);
		foreach ($cur_person as $k => $v) $final_opinion[$k] = $v;
		
		$step = $row['cur_step'] + 1;		
		//判断事务是否结束
		if(!isset($content[$step])){
			
			$data = [
					'cur_person' => json_encode($cur_person),
					'cur_aid' => '',
					'final_opinion' => json_encode($final_opinion)
			];
			
			$flag = Db::table('affair_table')->where(['id' => $id])->update(['state' => $result ? 1 : 0]);
			if(false === $flag) return false;
			
			//发送消息告知创建人
			$messageModel = new \app\common\model\Message();
			$msg = $result ? '您的工程业务订单审核通过' : '您的工程业务订单审核未通过';
			$remark = [];
			$messageModel->sendMessage(0, $row['create_by'], $msg, 2, '', url('manage/Affairengineering/orderDetailData', ['id' => $id]));
			return true;
		}else{
			//生成下一步处理人
			$juryUid = $this->getJury($content, $step);
			
			$data = [
					'cur_step' => $step,
					'cur_person' => json_encode([$juryUid => ['state' => 'chief', 'send_t' => time()]]),
					'cur_aid' => '',
					'cur_chief' => $juryUid,
					'final_opinion' => json_encode($final_opinion)
			];
			$flag = Db::table('affair_table')->where(['id' => $id])->update($data);
			if(false === $flag) return false;
			
			//发送消息告知审批人
			$messageModel = new \app\common\model\Message();
			$temp = $userModel->profile($row['create_by']);					
			$duty = [];
			foreach ($temp['role'] as $v) $duty[] = $v['identity'];
			$duty = implode('|', $duty);
			$link = json_encode(['pc' => url('manage/Order/exginfos', ['id' => $id]), 'wx' => url('wechat/Cons/ereview', ['id' => $id])]);
			$msg = "来自$duty{$temp['name']}的产品业务订单需要您审核，快去看看吧!";
			$messageModel->sendMessage(0, $juryUid, $msg, 2, '', $link);
		}

		$recordModel = new \app\common\model\Record();
		$recordModel->updateJuryMd5($row['id']);

		return true;
	}
	
	//判断当前步骤能否进行到下一步
	private function curStepPass(){
		
	}
	
	//获取当前步骤处理人
	public function getJury($content, $step){
		if(isset($content[$step]['persons'])) {
			//persons
			$persons = shuffle($content[$step]['persons']);
			return $content[$step]['persons'][0];
		}else{
			//duty
			//查出当前职位对应审核人的uid
			$rows = Db::table('relation')->distinct(true)->field('uid')->where(['rid' => ['in', $content[$step]['duty']]])->select();;
			shuffle($rows['uid']);
			return $rows['uid'][0];
		}
	}
	
	//审核人/辅助人进行处理
	public function  processAffair(){
		$id = input('?post.id') ? input('post.id') : exit;

		$row = Db::table('affair_table')->field('id,create_by,final_opinion,cur_person,cur_aid,state,order_no,order_name,cur_chief')->find($id);

		if(!$row) show(0, '参数错误');
		
		if($row['state'] !=-1) show(0, '操作失败,当前订单已处理结束');
		$cur_person = json_decode($row['cur_person'], true);
		$cur_aid = json_decode($row['cur_aid'], true);

		$userId = session('user.id');
		if(request()->isPost()){	
			//校验权限
			if(!isset($cur_person[$userId]) && !isset($cur_aid[$userId]))
				if(!$row) show(0, '非法访问');

			if(isset($cur_person[$userId])){
				//主审处理
				$action = input('post.action');
				$actonMap = ['chief' => 'actionChief', 'copy' => 'actionCopy', 'inquiry' => 'actionInquiry',
						'rework' => 'actionRework', 'modify' => 'actionModify'];
				if(!isset($actonMap[$action])) show(0, '无法进行当前操作');
				$res = call_user_func_array([$this, $actonMap[$action]], [json_encode($row)]);

				if($res) show(1, '操作成功'); else show(0, '操作失败，请重试!');
				
			}else{
				//征询人回复意见
				if($cur_aid[$userId]['state'] == 'inquiry'){
					
					$note = input('?post.note') ? input('post.note') : '';
					$cur_aid[$userId]['opinion'] = $note;
					$time = time();
					$cur_aid[$userId]['end_t'] = $time;
					Db::table('affair_table')->where(['id' => $row['id']])->update(['cur_aid' => json_encode($cur_aid)]);
						
					//发送消息
					$messageModel = new \app\common\model\Message();
					$content = "征询人".session('user.duty').session('user.name').'给出了意见';
					$link = json_encode(['pc' => url('manage/Order/exginfos', ['id' => $id]), 'wx' => url('wechat/Cons/ereview', ['id' => $id])]);
					$messageModel->sendMessage(0, $row['cur_chief'], $content, 1, '', $link);
					show(1, '操作成功');
				}
				
				//创建人重新填写订单
				if($cur_aid[$userId]['state'] == 'modify'){
					return [];
				}
			}
			//查看当前人操作是什么
		}
	}
	
	//主审审核
	private function actionChief($row){
		$row = json_decode($row, true);
		$note = input('?post.note') ? input('post.note') : '';
		$result = input('?post.result') ? input('post.result') : exit;
		$userId = session('user.id');
		
		//记录评审意见
		$cur_person = json_decode($row['cur_person'], true);
		$cur_person[$userId] = ['opinion' => $note, 'state' => 'chief', 'ent_t' => time(), 'send_t' => $cur_person[$userId]['send_t']];
		$final_opinion = json_decode($row['final_opinion'], true);
		$final_opinion[$userId] = $cur_person[$userId];
		$data = ['cur_person' => json_encode($cur_person), 'final_opinion' => json_encode($final_opinion)];
		
		if($result){
			//同意通过
			Db::table('affair_table')->where(['id' => $row['id']])->update($data);
		}else{
			
			//拒绝
			$data['state'] = 0;
			Db::table('affair_table')->where(['id' => $row['id']])->update($data);
			
			//发送消息
			$messageModel = new \app\common\model\Message();
			$content = '您的工程业务订单已被拒绝,订单号:'.$row['order_no'];
			$link = json_encode(['pc' => url('manage/Order/ginfos', ['id' => $row['id']]), 'wx' => url('wechat/Cons/businlistdetail', ['id' => $row['id']])]);
			$remark = json_encode(['note' => $note, 'reply' => '', 'time' => time()]);
			$messageModel->sendMessage(0, $row['create_by'], $content, 2, '', $link);
			return true;
		}
		
		$this->nextStep($row['id'], $result);
		return true;
	}
	
	//抄送
	private function actionCopy($row){
		$row = json_decode($row, true);
		$inqueryId = isset($_POST['injueryId']) ? $_POST['injueryId'] : exit;
		$cur_aid = json_decode($row['cur_aid'], true);
		if(!$cur_aid) $cur_aid = [];
		$time = time();
		//生成辅助征询人信息
		foreach ($inqueryId as $v)
			$cur_aid[$v['id']] = ['send_t' => $time, 'state' => 'copy', 'note' => $v['note']];
		
		Db::table('affair_table')->where(['id' => $row['id']])->update(['cur_aid' => json_encode($cur_aid)]);
		
		//发送消息
		$messageModel = new \app\common\model\Message();
		$content = '您收到来自'.session('user.duty').session('user.name').'产品订单的副本';
		foreach ($inqueryId as $v){
			$remark = json_encode(['note' => $v['note'], 'time' => $time, 'id' => $row['id']]);
			$msgId = $messageModel->sendMessage(0, $v['id'], $content, 2, $remark, '');
			$link = json_encode(['pc' => url('manage/Order/gcopy', ['id' => $msgId]), 'wx' => url('wechat/Cons/enginCopy', ['id' => $msgId])]);
			Db::table('message')->where(['id' => $msgId])->update(['link' => $link]);
		}
		return true;
	}
	
	//征询
	private function actionInquiry($row){
		$row = json_decode($row, true);
		$inqueryId = isset($_POST['injueryId']) ? $_POST['injueryId'] : exit;

		$cur_aid = json_decode($row['cur_aid'], true);
		if(!$cur_aid) $cur_aid = [];
		$time = time();
		//生成辅助征询人信息
		foreach ($inqueryId as $v) 
			$cur_aid[$v['id']] = ['send_t' => $time, 'state' => 'inquiry', 'note' => $v['note'], 'opinion' => '', 'end_t' => '']; 
		
		Db::table('affair_table')->where(['id' => $row['id']])->update(['cur_aid' => json_encode($cur_aid)]);
		
		//发送消息
		$messageModel = new \app\common\model\Message();
		$content =session('user.duty').session('user.name').'有份工程订单需征询您的意见';
		$link = json_encode(['pc' => url('manage/Order/ginquiry', ['id' => $row['id']]), 'wx' => url('wechat/Cons/ginquiry', ['id' => $row['id']])]);
		foreach ($inqueryId as $v){
			$remark = json_encode(['note' => $v['note'], 'reply' => '', 'time' => $time]);
			$messageModel->sendMessage(0, $v['id'], $content, 2, $remark, $link);
		}
		return true;
	}
	
	//重修
	private function actionRework($row){
		$row = json_decode($row, true);
		$note = input('?post.note') ? input('post.note') : '';
		$userId = session('user.id');
		$cur_person = json_decode($row['cur_person'], true);
		$time = time();
		$cur_person[$userId]['opinion'] = $note;
		$cur_person[$userId]['end_t'] = time();
		Db::table('affair_table')->where(['id' => $row['id']])->update( ['cur_person' => json_encode($cur_person), 'state' => 0]);
		//结束流程记录数据库
		//生成消息内容，发送消息
		$messageModel = new \app\common\model\Message();
		$orderInfo = $this->orderDetailData($row);
		$content = '很遗憾，您的工程业务订单未能通过，请修改后重新提交!';
		$link = json_encode(['pc' => url('manage/Order/ginfos', ['id' => $row['id']]), 'wx' => url('wechat/Cons/businlistdetail', ['id' => $row['id']])]);
		$messageModel->sendMessage(0, $row['create_by'], $content, 2, '', $link);
	}
	
	//返修
	private function actionModify($row){    
		$row = json_decode($row, true);
		//发送消息给订单人
		//将当前辅助人设为用户状态为返修
		$note = input('?post.note') ? input('post.note') : '';
		$cur_aid = json_decode($row['cur_aid'], true);
		$cur_aid[$row['create_by']] = ['state' => 'modify', 'note' => $note, 'send_t' => time()];
		Db::table('affair_table')->where(['id' => $row['id']])->update(['cur_aid' => json_encode($cur_aid, true)]);
		//发送消息
		$messageModel = new \app\common\model\Message();
		$remark = json_encode(['note' => $note, 'state' => 'modify', 'order_no' => $row['order_no'], 'id' => $row['id'], '']);
		$content = '您的产品业务订单需要您修改信息后才能继续进行';
		$messageModel->sendMessage(0, $row['create_by'], $content, 2, url('manage/Affairorder/orderDetail'),$remark);
	}
	
	
	public function test(){
		$userModel = new \app\manage\controller\User();
		$res = $userModel->profile(20);
	}
	
	
	public function orderDetailData(){
		$id = input('?post.id') ? input('post.id') : exit;
		$row = Db::table('affair_table')
					->field('order_no,state,create_by,cur_step,cur_person,charge,cur_aid')
					->find(['id' => $id]);

		//判断用户权限
// 		if(session('user.id') != $row['create_by']) show(0, '您没有该权限');
		//基础信息
		$userModel = new User();
		$temp = $userModel->profile($row['create_by']);
		
		foreach ($temp['role'] as $v) $duty[] = $v['identity'];
		$duty = implode('|', $duty);
		$data['base']['create'] = ['name' => $temp['name'], 'duty' => $duty];
		if(!empty($row['charge'])){
			$temp = $userModel->profile($row['charge']);
			$duty = [];
			foreach ($temp['role'] as $v) $duty[] = $v['identity'];
			$duty = implode('|', $duty);
			$charge = ['name' => $temp['name'], 'duty' => $duty];
			$data['base']['charge'] = $charge;
		}
		
		//工程信息
        $order = $this->orderDetail($row['order_no']);
		
        $data['order'] = [
            'name' => $order['cname'],
            'order_no' => $order['eid'],
            'time' => $order['ct'],
            'content' => $order['content'],
            'cycles' => $order['cycles'],
            'acamount' => $order['amoneys'],
            'url' => $order['contract'],
            'remarks' => $order['remarks']
		];


		//评审信息
        $cur_person = json_decode($row['cur_person'], true);
        $juryId = key($cur_person);
        $duty = [];
        $temp = $userModel->profile(key($cur_person));
		foreach ($temp['role'] as $v) $duty[] = $v['identity'];
		$duty = implode('|', $duty);
		$jury = ['name' => $temp['name'], 'duty' => $duty];
		$res = Db::table('affair_default_process')->field('content')->where(['type' => self::$type])->find();
		$steps = count(json_decode($res['content'], true));
		$data['jury'] = ['juryMan'=> $jury, 'curStep' => $row['cur_step'], 'steps' => $steps, 'type' => $row['state']];
		
		if($row['state'] != -1) $data['jury']['juryMan']['note'] = @$cur_person[$juryId]['opinion'] ? $cur_person[$juryId]['opinion'] : '';
		
		//辅助人员信息
		$cur_aid = json_decode($row['cur_aid'], true);
		if(!$cur_aid) $cur_aid = [];
		
		foreach ($cur_aid as $k => $v){
			$tempRow = Db::table('user')->field('name')->find($k);
		
			$assistMan[$k] = $v;
			$assistMan[$k]['name'] = $tempRow['name'];
		}
		if(@$assistMan) $data['jury']['assistMan'] = $assistMan;
		
		
		show(1, '操作成功', $data);
	}
	
	//查看订单详情
	private function orderDetail($order_no){
		$order = Db::table('engin')->where(['eid' => $order_no])->find();
        return $order;
	}
	
	//用户催单
	public function reminder(){
		$id = input('post.id');
	}
	
	//征询意见
	public function inquiry(){
		$id = input('?post.id') ? input('post.id') : exit;
		$row = Db::table('affair_table')->field('cur_person,create_by,order_no,cur_aid,charge')->find($id);
		$userId = session('user.id');
		$cur_aid = json_decode($row['cur_aid'], true);
		if(!isset($cur_aid[$userId])) show(0, '当前状态链接已失效');
		
		//基础信息
		$userModel = new \app\manage\controller\User();
		$temp = $userModel->profile($row['create_by']);
		foreach ($temp['role'] as $v) $duty[] = $v['identity'];
		$duty = implode('|', $duty);
		$data['base']['create'] = ['name' => $temp['name'], 'duty' => $duty];
		
		if(!empty($row['charge'])){
			$temp = $userModel->profile($row['charge']);
			$duty = [];
			foreach ($temp['role'] as $v) $duty[] = $v['identity'];
			$duty = implode('|', $duty);
			$charge = ['name' => $temp['name'], 'duty' => $duty];
			$data['base']['charge'] = $charge;
		}
		
		//订单信息
		$order = $this->orderDetail($row['order_no']);
		
        $data['order'] = [
            'name' => $order['cname'],
            'order_no' => $order['eid'],
            'time' => $order['ct'],
            'content' => $order['content'],
            'cycles' => $order['cycles'],
            'acamount' => $order['amoneys'],
            'url' => $order['contract'],
            'remarks' => $order['remarks']
		];
		
		//处理人
		$cur_person = json_decode($row['cur_person'], true);
		$temp = $userModel->profile(key($cur_person));
		$duty = [];
		foreach ($temp['role'] as $v) $duty[] = $v['identity'];
		$duty = implode('|', $duty);
		$jury = ['name' => $temp['name'], 'duty' => $duty, 'note' => $cur_aid[$userId]['note'], 'time' => $cur_aid[$userId]['send_t']];
		$data['jury'] = ['juryMan'=> $jury];
		show(1, '操作成功', $data);
	}
	
	//抄送界面
	public function copy(){
		$id = input('?post.id') ? input('post.id') : exit;
		$remark = Db::table('message')->field('remark')->find($id);
		$remark = json_decode($remark['remark'], true);
		$row = Db::table('affair_table')->field('cur_person,create_by,order_no,cur_aid,charge')->find($remark['id']);
		$userId = session('user.id');
		
		//基础信息
		$userModel = new \app\manage\controller\User();
		$temp = $userModel->profile($row['create_by']);
		foreach ($temp['role'] as $v) $duty[] = $v['identity'];
		$duty = implode('|', $duty);
		$data['base']['create'] = ['name' => $temp['name'], 'duty' => $duty];
		
		if(!empty($row['charge'])){
			$temp = $userModel->profile($row['charge']);
			$duty = [];
			foreach ($temp['role'] as $v) $duty[] = $v['identity'];
			$duty = implode('|', $duty);
			$charge = ['name' => $temp['name'], 'duty' => $duty];
			$data['base']['charge'] = $charge;
		}
		
		//工程信息
		$order = $this->orderDetail($row['order_no']);
		
        $data['order'] = [
            'name' => $order['cname'],
            'order_no' => $order['eid'],
            'time' => $order['ct'],
            'content' => $order['content'],
            'cycles' => $order['cycles'],
            'acamount' => $order['amoneys'],
            'url' => $order['contract'],
            'remarks' => $order['remarks']
		];
		
		//审核人信息
		$cur_person = json_decode($row['cur_person'], true);
		$duty = [];
		$temp = $userModel->profile(key($cur_person));
		foreach ($temp['role'] as $v) $duty[] = $v['identity'];
		$duty = implode('|', $duty);
		$jury = ['name' => $temp['name'], 'duty' => $duty, 'note' => $remark['note'], 'time' => $remark['time']];
		
		$data['jury'] = $jury;
		show(1, '操作成功', $data);
	}
	
	//重修
	public function rework(){
		$id = input('?post.id') ? input('post.id') : exit;
		$row = Db::table('affair_table')
					->field('order_no,state,create_by,cur_person,cur_step,cur_aid,charge,transport,arrival_t,logistics')
					->find(['id' => $id]);
		
		
		//判断用户权限
		if(session('user.id') != $row['create_by']) show(0, '您没有该权限');
		
		//基础信息
		$userModel = new \app\manage\controller\User();
		$temp = $userModel->profile($row['create_by']);
		foreach ($temp['role'] as $v) $duty[] = $v['identity'];
		$duty = implode('|', $duty);
		$data['base']['create'] = ['name' => $temp['name'], 'duty' => $duty];
		
		if(!empty($row['charge'])){
			$temp = $userModel->profile($row['charge']);
			$duty = [];
			foreach ($temp['role'] as $v) $duty[] = $v['identity'];
			$duty = implode('|', $duty);
			$charge = ['name' => $temp['name'], 'duty' => $duty];
			$data['base']['charge'] = $charge;
		}
		
		//工程信息
		$order = $this->orderDetail($row['order_no']);
        $data['order'] = [
            'name' => $order['cname'],
            'order_no' => $order['eid'],
            'time' => $order['ct'],
            'content' => $order['content'],
            'cycles' => $order['cycles'],
            'acamount' => $order['amoneys'],
            'url' => $order['contract'],
            'remarks' => $order['remarks']
		];
		
		//审核人意见
		$cur_person = json_decode($row['cur_person'], true);
		$key = key($cur_person);
		$temp = $userModel->profile($key);
		$duty = [];
		foreach ($temp['role'] as $v) $duty[] = $v['identity'];
		$duty = implode('|', $duty);
		$data['jury']['juryMan'] = [
				'name' => $temp['name'],
				'duty' => $duty, 
				'note' => @$cur_person[$key]['opinion'],
				'time' => @$cur_person[$key]['end_t']
		];
		show(1, '操作成功', $data);
	}
	
	//返修
	public function modify(){
		return view();
	}
	
	private function orderJuryDetail($id){
	}
	
}
